package com.instalinks.android.apps.receiver;

import com.instalinks.android.lib.LibConstants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

		Bundle bundle = intent.getExtras();

		SmsMessage msgs = null;
		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");

			for (int i = 0; i < pdus.length; i++) {
				msgs = SmsMessage.createFromPdu((byte[]) pdus[i]);
				
				String sender = msgs.getOriginatingAddress();
				String text = msgs.getMessageBody();
				
				broadcastSms(context, sender, text);
			}
		}
	}
	
	private void broadcastSms(Context context,String sender, String text) {

		Intent i = new Intent();
		i.setAction(com.instalinks.android.lib.LibConstants.IntentAction.SMS_BROADCAST);

		Bundle bundle = new Bundle();
		bundle.putString(LibConstants.BroadcastFields.mode, "sms_interceptor");
		bundle.putString(LibConstants.BroadcastFields.appid, context.getPackageName());
		bundle.putString(LibConstants.BroadcastFields.sender, sender);
		bundle.putString(LibConstants.BroadcastFields.text, text);
		i.putExtras(bundle);

		context.sendBroadcast(i);

	}
	
}
